$(function () {
    var prodAndLogTimer;
    var devTimer;

	//将缓存中的值放入Input框
	var d  = layui.data('sInfo');
	var minCode  = $("#minCode").val();
	var maxCode  =  $("#maxCode").val();
	if(!!d&&!!d.data){
		d = d.data;
		console.log("从缓存设置值");
		minCode = d[0].value;
		maxCode = d[1].value;
		$("#minCode").val(minCode);
		$("#maxCode").val(maxCode);
	}
	
	var redirect = $("#redirect").val();
	if("1"==redirect){
		window.location.href = "http://10.21.2.24:28820/ims-mes/agedev/ageDevIndex";
		return;
	}
	
    //getDataByPage(null,null);

    //请求后台数据
    //卡片状态 "default":闲置 "normal":运行 "ficing":升级 "error":不良 "finish":完成
    function getDataByPage(curr,pageSize){
		
        var paraData = {};
        if(curr!=null){
            paraData = {"curr":curr,"pageSize":pageSize,"minCode":minCode,"maxCode":maxCode};
        }
		//先加载一次
		loadData(paraData);
        if(!!devTimer)clearInterval(devTimer);
        devTimer = setInterval(function(){
       	  loadData(paraData);
        }, 20000);
    }

	//加载数据
	function loadData(paraData){
			var d  = layui.data('sInfo');
			if(!!d&&!!d.data){
				d = d.data;
				minCode = d[0].value;
				maxCode = d[1].value;
				$("#minCode").val(minCode);
				$("#maxCode").val(maxCode);
			}else{
				minCode = $("#minCode").val().trim();
				maxCode = $("#maxCode").val().trim();
			}
			
			paraData.minCode = minCode;
			paraData.maxCode = maxCode;
		
		   $.ajax({
                type:"post",
                url:contextPath+"/agedevall/listAgeDevBindInfoAll",
                data:paraData,
				async:false,
                success:function(resp){
                    var finalData = [];
                    //渲染卡片数据
                    if(!!resp.data){
						$("#stockCount").text(resp.headInfoAll.stockNum+"-"+resp.data.length);
                        resp.data.forEach(function(d,index){
                            var devInfo = {};
                            var detail = [];
                            devInfo.title = d.stockCode;
							devInfo.moId = d.moId;
							devInfo.lbId = d.lbId;
							if(!!d.lbId)detail.push({"name":"标签编码","value":d.lbId});
							var flag = false;
                            if(!!d.mesAgeDevInfoDto){//有设备信息
								//detail.push({"name":"设备编码","value":d.mesAgeDevInfoDto.devNo});
								//detail.push({"name":"工单编码","value":d.mesAgeDevInfoDto.moCode});
								var lhMsg = d.mesAgeDevInfoDto.startTime;
								var diffMin = d.mesAgeDevInfoDto.diffMin;
								var nowVersion = d.mesAgeDevInfoDto.nowVersion;
								var isPass = d.mesAgeDevInfoDto.isPass;
								var passMsg = "未老化完";
								if("Y"==isPass){
									passMsg = "老化完成";
									flag = true;
								}
								if(!!diffMin){
									if(diffMin<0)diffMin=0;
									lhMsg+= " "+diffMin+"分钟";
								}
								detail.push({"name":"老化信息","value":lhMsg});
								if(!!nowVersion){
									detail.push({"name":"已升级为","value":nowVersion});
									detail.push({"name":"状态","value":passMsg});
								}
								devInfo.ageDevInfoId = d.mesAgeDevInfoDto.ageDevInfoId;
                            }
							//设置颜色信息
							//debugger;
							setShowColor(d,devInfo,detail,flag);
                            devInfo.list = detail;
                            finalData.push(devInfo);
                        })
                    }
                    //渲染头部数据
                    if(!!resp.headInfoAll){
                        $("#def").html(resp.headInfoAll.def+"-"+resp.headInfo.def);//闲置
                        $("#normal").html(resp.headInfoAll.normal+"-"+resp.headInfo.normal);//在线
                        $("#finish").html(resp.headInfoAll.finish+"-"+resp.headInfo.finish);//完成
                        $("#error").html(resp.headInfoAll.error+"-"+resp.headInfo.error);//未连接
 						$("#ficing").html(resp.headInfoAll.cusfinish+"-"+resp.headInfo.cusfinish);//客制完成
						$("#unconn").html(resp.headInfoAll.unconn+"-"+resp.headInfo.unconn);//断开
                    }
 				//	$("#time").html(resp.time);//时间
					$("#port").html(resp.port);//端口
					if(!!resp.ip)$("#ip").html(resp.ip);
                    vm.listData = finalData;
                }
            })

			console.log("===3==");
	}
	
	setInterval(function(){
		var date = new Date();
		year = date.getFullYear();
		month = date.getMonth()+1;
		day = date.getDate();
		hours = date.getHours();
		min = date.getMinutes();
		sec = date.getSeconds()<9?'0'+date.getSeconds():date.getSeconds();		
		$("#time").html(year+"-"+month+"-"+day+"-"+hours+":"+min+":"+sec);
	},1000);


/**
*设置颜色
 */
	function setShowColor(d,devInfo,detail,flag){
		//debugger;
		switch(d.showType){
			case "def":
				   devInfo.state = "default"
				break;
			case "logoError":
				   devInfo.state = "logoError"
				break;
			case "videoError":
				   devInfo.state = "videoError"
				break;
			case "normal"://正常连接
				   devInfo.state = "normal"
					detail.push({"name":"在线时长","value":d.mesAgeDevInfoDto.upgradeMin+"分钟"});
				break;	
			case "unconn"://断开
				   devInfo.state = "warning"
					if(d.waitMin==null)d.waitMin=0;
					if(d.waitMin>15){
						detail.push({"name":"等待时间：","value":"等待连接超过15分钟"});
					}else{
						detail.push({"name":"等待时间","value":d.waitMin+"分钟"});
					}
                    detail.push({"name":"重启服务器","value":"请尝试重启服务器...."});
				break;		
				case "finish":
				   devInfo.state = "finish"
				 	 if(flag){
						 devInfo.state = "isover";
					}
				break;	
				case "error":
				   devInfo.state = "error"
				break;		
				case "cusfinish":
				   detail.push({"name":"升级信息","value":"已升级"});
				   devInfo.state = "ficing"
				break;			
			default:
		}
	}

    // 创建 Vue 实例，得到 ViewModel
    var vm = new Vue({
        el: '#app',
        data: {
            sumPage: 100,//总页数
            current: 1,//当前页数
            listNum: 0,//当前页一页卡片最大数量
            lineNum: 0,//当前页行数
            column: 12,//当前页列数
	    istitle:false, 
            listData: [],
            popUp: false,//控制弹窗
            popData: {
                title: "00-00",
                tapShow: "",//空显示产品信息，'log'显示日志
                list: [

                ],
                logData: [],
            },
            colStyle: {},
        },
        mounted: function () {
            let _this = this;
            this.$nextTick(() => {
                _this.getCardStyle();
		getDataByPage(this.current, this.listNum)
                //初始化弹窗内容滚动
                $(this.$refs.centerBox).mCustomScrollbar({
                    theme: 'minimal',
                    scrollInertia: 550,
                    mouseWheelPixels: 220,
                });
            })
        },
        methods: {
			clickTopBtnOne: function () {//点击头部按钮1
                    this.istitle = !this.istitle
                    if(this.istitle == true){
                        this.$refs.titleBtn.$el.innerHTML = '隐藏标题'
                    }else{
                        this.$refs.titleBtn.$el.innerHTML = '显示标题'
                    }
            },
            clickTopBtnOne: function () {//停止刷新
                if($("#clickTopBtnOne").text()=="停止刷新"){
                    $("#clickTopBtnOne").text("刷新");
                    if(!!devTimer)clearInterval(devTimer);
                    if(!!prodAndLogTimer)clearInterval(prodAndLogTimer);
                }else{
                    $("#clickTopBtnOne").text("停止刷新");
                    getDataByPage(this.current,this.listNum);
                }
            },
            clickTopBtnTwo: function () {//回到首页
                getDataByPage(1,this.listNum);
                this.current = 1;
            },
            clickTopBtnThree: function () {//设置查询区间
				//先从缓存拿，拿不到设置为页面的
				var d  = layui.data('sInfo');
				var minCode  = $("#minCode").val();
				var maxCode  =  $("#maxCode").val();
				if(!!d&&!!d.data){
					d = d.data;
					console.log("==="+d);
					minCode = d[0].value;
					maxCode = d[1].value;
					console.log("===>缓存数据区间最小值："+minCode);
					console.log("===>缓存数据区间最大值："+maxCode);
				}
				$("#minCode").val(minCode);
				$("#maxCode").val(maxCode);
				layer.open({
	        		title:['柜号查询设置'],
	        		area:['30%'],
					type:1,
	        		content:$("#showBox"),
		    		cancel:function(){
						minCode = $("#minCode").val();
						maxCode = $("#maxCode").val();
						console.log(minCode+"==="+maxCode);
						//设置到本地缓存
						var d = {key:'data',value:[{key:"minCode",value:minCode},{key:"maxvalue",value:maxCode}]};
						layui.data('sInfo',d);
	            	},yes:function(){
						layer.closeAll();
					}
	        	});
            },
            columnChange: function (num) {//列数输入框变化
                this.getCardStyle();//计算样式以及总页数
                console.log("列数输入框变化,当前" + num + "列一行");
                console.log("每页数据最大数量：" + this.listNum);

            },
            prePage: function (current) {//点击上一页
                console.log("上一页:第" + current + "页");
                console.log("当前每一页条数:" + this.listNum);
                if(current>0){
                    getDataByPage(current,this.listNum);
                    this.current--;
                }else{
                    this.current=1;
                }
            },
            nextPage: function (current) {//点击下一页
                console.log("下一页:第" + current + "页");
                console.log("当前每一页条数:" + this.listNum);
                getDataByPage(current,this.listNum);
                this.current++;
            },
            relink: function (data) {//点击弹窗重新连接按钮
                console.log(data);
                console.log("重新连接")
				relink(this,data);	
            },
            reupgrade: function (data) {//点击弹窗重新升级按钮
                console.log(data)
                reUpgrade(this,data);
                console.log("重新升级")
            },
            release: function (data) {//点击弹窗站点释放按钮
                console.log(data)
                console.log("站点释放")
                releaseBindInfo(this,data);
            },
            closePopUp: function () {//关闭弹窗
                console.log("关闭弹窗")
                if(!!prodAndLogTimer)clearInterval(prodAndLogTimer);
                this.popUp = false;
                //清空定时任务
            },
            carsClick: function (data) {//点击卡片
                console.log(JSON.stringify(data)+"===卡片数据==");
				if(!data.list[1].value)return;
                 viewDetailInfo(this,data)
	             this.popUp = true;
            },
            setPopTapShow: function (name) {//点击弹窗tap
                if (!name) {
                    this.popData.tapShow = '';
                } else {
                    this.popData.tapShow = name;
                }
            },
            getCardStyle: function () {//获取卡片样式
               let _this = this;
                let style = {};
                style.width = (100 / Number(this.column) - 0.001) + "%";
                style.float = "left";
                style.padding = "0.02rem";
                let contentHeigh = _this.$refs.content.offsetHeight;
                _this.lineNum = parseInt(contentHeigh / 145);
                _this.listNum = _this.lineNum * Number(_this.column);
                let pro = 100 / _this.lineNum;
                style.height = pro + "%";
                _this.colStyle = style;
            }

        },
        watch: {
            column: function (newVla, oldVla) {
                if (newVla || newVla === 0) {
                    this.columnChange(newVla);
                }
            }
        },
        computed: {

        },
    });


	/**
	    *   重新连接（重新连接超过五次的连接）
	 */
	function relink(obj,data){
		 $.ajax({
            type:"post",
			async:false,
            url:contextPath+"/agedevall/relink",
             data:{"ageDevInfoId":data.ageDevInfoId,"moId":data.moId},
            success:function(resp){
                if(!!resp){
					layer.msg(resp.msg,{skin:'layui-layer-molv'});
                }
            }
        });
	}

    /**
             * 重新升级
     * @param obj
     * @param data
     */
    function reUpgrade(obj,data){
	var layer = layui.layer;
        $.ajax({
            type:"post",
			async:false,
            url:contextPath+"/agedevall/reUpgrade",
            data:{"ageDevInfoId":data.ageDevInfoId,"moId":data.moId},
            success:function(resp){
                if(!!resp){
					layer.msg(resp.msg,{skin:'layui-layer-molv'});
                }
            }
        });
    }

    /**
               * 释放站点
     * @param obj
     * @param data
     */
    function releaseBindInfo(obj,data){
	
		layer.confirm('确定释放吗？释放后将解除与货架的绑定',{icon:5,title:'站点释放'},function(){
			  $.ajax({
					async:false,
		            type:"post",
		            url:contextPath+"/agedevall/release",
		            data:{"stockCode":data.title},
		            success:function(resp){
		                if(!!resp){
							layer.msg(resp.msg,{skin:'layui-layer-molv'});
		                }
		            }
		        });
			
		});
	
      
    }

    /**
   /    * 加载产品信息
     * @param obj
     * @param data
     */
    function viewDetailInfo(obj,data){
        obj.popData.title = data.title;
		obj.popData.moId= data.moId;
		obj.popData.ageDevInfoId= data.ageDevInfoId;
        prodAndLogTimer =  setInterval(function(){
            //获取产品信息
            $.ajax({
				async:false,
                type:"post",
                url:contextPath+"/agedevall/listAgeDevInfoAll",
                //data:{"ageDevInfoId":"605507087208091648","moId":"601722185434075136","lbId":"W210322S0004",},
				//测试注释，需要恢复
				data:{"ageDevInfoId":data.ageDevInfoId,"moId":data.moId,"lbId":data.lbId,},
                success:function(resp){
                    var detail = [];
					if(!!resp&&!!resp[0]){
						 resp = resp[0];
	                    detail.push({"name":"设备编码","value":resp["devNo"]});

	                    var connName = "断开";
	                    if(1==resp["connStatus"]){
	                        connName="连接";
	                    }else if(2==resp["connStatus"]){
	                        connName="重联";
	                    }else if(0==resp["connStatus"]){
							 connName = "断开";
						}else{
							 connName = "未连接";
						}
						var total = 0;
						if(!!resp["ageTime"]){
							total = resp["ageTime"]*60;
						}else{
							total = resp["ageTime"]=0;
						}
						var upName = "未完成";
	                    if(1==resp["isOver"]){
	                        upName="已完成";
	                    }else if(0==resp["isOver"]){
	                        upName="未级中";
	                    }else{
							upName="升级中";
						}
						
	                   detail.push({"name":"联接状态","value":connName});
						if(!!resp["devNo"]){
	                   		 detail.push({"name":"升级状态|进度","value":upName+" | "+resp["inprogress"]+"%"});
						}else{
							 detail.push({"name":"升级状态|进度","value":"未升级|0%"});
						}
	                    detail.push({"name":"网络地址","value":"/"});
	                    detail.push({"name":"logo上传次数","value":resp["logoCount"]});
	                    detail.push({"name":"视频验证次数","value":resp["chkVideoResult"]});
	                    detail.push({"name":"硬盘可用/总容量","value":resp["storageLast"]+"/"+resp["storageTotal"]});
	                    detail.push({"name":"扫描开始时间","value":resp["scaleTime"]});
	                    detail.push({"name":"产品编码","value":resp["prodCode"]});
	                    detail.push({"name":"工单单号","value":resp["moCode"]});
   						detail.push({"name":"erp工单号","value":resp["erpMo"]});
	                    detail.push({"name":"平台版本","value":resp["platType"]=="1"?"自主平台":"客供平台"});
	                    detail.push({"name":"最新联接时间","value":resp["connTime"]});
	                    detail.push({"name":"联接次数","value":resp["connCount"]});
	 					detail.push({"name":"老化需要总时长","value":total+"分钟"});
	                    detail.push({"name":"已在线时长","value":resp["upgradeMin"]+"分钟"});
	                    detail.push({"name":"产品版本","value":resp["softVersion"]});
	                    detail.push({"name":"软件路径1","value":resp["ftpPath1"]});
	                    detail.push({"name":"软件版本1","value":resp["ftpSoft1"]});
   						detail.push({"name":"标签编码","value":resp["lbId"]});
						detail.push({"name":"mac地址","value":resp["macAddr"]});
					}
	                 obj.popData.list = detail;
                }
            });
            //获取日志信息
            $.ajax({
                type:"post",
				async:false,
                url:contextPath+"/agedevall/listAgeDevInfoLogAll",
                data:{"ageDevInfoId":data.ageDevInfoId},
                success:function(resp){
                    var detail = [];

                    resp.forEach(function(d,index){
                        if(d.inprogress!=undefined&&d.inprogress!=null){
                            detail.push({"text":d.content+"  当前进度 "+d.inprogress+"%","time":d.createdDateNew});
                        }else{
                            detail.push({"text":d.content,"time":d.createdDateNew});
                        }
                    })
                    console.log(JSON.stringify(resp)+"==detail==");
                    obj.popData.logData =detail ;
                }
            });

        },1000);
    }

});
